<template>
  <div> 
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="id" label="序号" />
      <el-table-column prop="name" label="商品名称" />
      <el-table-column prop="category" label="商品分类" />
      <el-table-column prop="price" label="价格" />


      <el-table-column label="商品图片" width="80">
        <template #default="scope">
          <img v-if="scope.row.imgUrl" :src="serverUrl+scope.row.imgUrl" class="goods-image" style="height: 40px;"/>
          <el-icon v-else icon="el-icon-picture" class="no-image" />
        </template>
         
      </el-table-column>


      <el-table-column label="创建时间" prop="ctime" :formatter="formatTime" />
      <el-table-column prop="rating" label="评价" />
      <el-table-column prop="sellCount" label="销量" />
      <el-table-column prop="goodsDesc" label="商品描述" show-overflow-tooltip />

      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button type="primary" size="small" @click="editbtn(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="del(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="page">
      <el-pagination
        v-model:current-page="formdata.currentPage"
        v-model:page-size="formdata.pageSize"
        :page-sizes="[5, 10, 20, 30]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="sizeChange"
        @current-change="currentPage"
      />
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { goodsList, delGoods } from '@/api/account'
import dayjs from 'dayjs'
import { ElMessage, ElMessageBox } from 'element-plus'
import { serverUrl } from '@/utils/common';

const tableData = ref([])
const total = ref(0)

const formdata = ref({
  currentPage: 1,
  pageSize: 10
})

// 获取商品列表
const getList = async () => {
  try {
    const res = await goodsList(formdata.value)
    console.log(res);
    tableData.value = res.data
    total.value = res.total
  } catch (error) {
    ElMessage.error('获取商品列表失败')
    console.error(error)
  }
}

// 初始化加载数据
getList()

// 页码改变
const currentPage = (val) => {
  formdata.value.currentPage = val
  getList()
}

// 每页条数改变
const sizeChange = (val) => {
  formdata.value.pageSize = val
  getList()
}

// 格式化时间
const formatTime = (row, column, cellValue) => {
  return dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss')
}

// 删除商品
const del = async(id) => {
  console.log(id);
  let res = await delGoods({id});
  console.log(res);
  if (res.code == 0) {
    ElMessage.success('删除成功');
    getList();
  } else {
    ElMessage.error('删除失败');
  }
  
};

// 编辑商品
const editbtn = (row) => {
  // 这里可以跳转到编辑页面或打开编辑弹窗
  console.log('编辑商品:', row)
}
</script>

<style scoped lang="scss">
.page {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

.el-image {
  cursor: pointer;
}
</style>